//
//  RequestViewController.swift
//  TestProject
//
//  Created by 万想想 on 2020/8/19.
//  Copyright © 2020 edaili. All rights reserved.
//

import UIKit

class RequestViewController: UIViewController {

    @IBOutlet var resultLabel: UILabel!
    var resultModel = ResultModel(){
        didSet{
            insertModelToTable()
        }
    }
    var response = String(){
        didSet{
            showResult()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "数据请求"
        view.backgroundColor = .white
        setRightButtonItem()
        Timer.shareInstance.timerIsCancel = true
        Timer.shareInstance.setEventHandler { [weak self] in
            self?.getData()
        }
        let rows = RequestTable.shareInstance.select()
        if rows.count > 0{
            resultLabel.text = rows[0][RequestTable.shareInstance.response]
        }
    }

    func setRightButtonItem(){
        let rightButtonItem = UIBarButtonItem.init(title: "历史记录", style: .plain, target: self, action: #selector(rightButtonItemAction))
        navigationItem.rightBarButtonItem = rightButtonItem
    }
    
    @objc func rightButtonItemAction(){
        let vc = HistoryViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    func getData(){
        NetWorkRequest(.getEndpoint, completion: {[weak self] (response) -> (Void) in
            let model = ResultModel()
            model.response = response
            model.currentTime = Tool.getCurrentYearMonthDayHourMinuteSecond()
            self?.resultModel = model
            self?.response = response
        }) { (message) -> (Void) in
            print(message)
        }
    }
    
    func showResult(){
        resultLabel.text = response
    }
    func insertModelToTable(){
        RequestTable.shareInstance.add(result: resultModel)
    }
}
